package com.fingard.dsp.bank.directbank.spdb01.authforrec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketHelper {
    /**
     * 发送报文
     *
     * @return
     * @throws UnknownHostException
     * @throws IOException
     */
    public static byte[] sentPacket(String ip, int port, byte[] content) throws UnknownHostException, IOException {
        // 连接远程服务器。请填写自己的IP和PORT
        Socket client = new Socket(ip, port);
        // 获取输出流
        OutputStream os = client.getOutputStream();
        // 输出
        os.write(content);
        os.flush();
        // 关闭输出流
        client.shutdownOutput();

        // 获取输出流
        InputStream in = client.getInputStream();
        byte[] data = readBytes(in);
        System.out.println(new String(data));
        // 关闭输入流
        client.shutdownInput();

        // 关闭连接
        client.close();
        return data;
    }

    /**
     * 读取in中所有字节
     *
     * @param in
     * @return
     * @throws IOException
     */
    public static byte[] readBytes(InputStream in) throws IOException {
        byte[] data = new byte[1024];
        byte[] dataTemp;
        int off = 0;
        int readLen = 0;
        int len = data.length - off;
        while ((readLen = in.read(data, off, len)) != -1) {

            off += readLen;
            len -= readLen;

            if (len == 0) {
                // 扩容
                dataTemp = new byte[data.length * 2];
                System.arraycopy(data, 0, dataTemp, 0, off);
                data = dataTemp;
                len = data.length - off;
            }
        }

        // 去除多余的字节
        dataTemp = new byte[off];
        System.arraycopy(data, 0, dataTemp, 0, off);
        return dataTemp;
    }

    /**
     * 读取len个字节
     *
     * @param in
     * @param len
     * @return
     * @throws Exception
     */
    public static byte[] readBytes(InputStream in, int len) throws Exception {
        byte[] data = new byte[len];
        int off = 0;
        int readLen = 0;
        while ((readLen = in.read(data, off, len)) != -1) {
            off += readLen;
            len -= readLen;
        }
        if (readLen != 0) {
            throw new Exception("读取len个字节失败，因为输入流in不可预料的关闭。");
        }
        return data;
    }
}
